package com.bw.controller;

import cn.hutool.captcha.generator.RandomGenerator;
import com.bw.domain.Role;
import com.bw.domain.User;
import com.bw.service.UserService;
import com.bw.utils.R;
import com.bw.utils.SmsUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author bobo棒
 * @date 2025年02月21日 11:34
 * 登录模块
 */

@RequestMapping("auth")
@Controller
public class AuthController {

    @Autowired
    UserService userService;
    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 执行登录
     *
     * @param phone
     * @param vercode
     * @return
     */
    @ResponseBody
    @RequestMapping("login")
    public R login(String phone, String vercode, HttpSession session) {
        //获取redis存储的验证码
        String codeRedis = (String) redisTemplate.opsForValue().get(phone);
        if (codeRedis == null) {
            return R.ERROR(500, "验证码已过期");
        }
        if (!codeRedis.equals(vercode)) {
            return R.ERROR(500, "验证码错误");
        }
        //根据手机号查询用户信息
        User user = userService.selectByPhone(phone);
        if (user == null) {
            return R.ERROR(500, "该手机号未注册");
        }
        //登录成功-存储session
        session.setAttribute("user", user);
        //查询用户的角色信息-并存入session
      List<Role> roleList=  userService.listRoleByUserId(user.getId()+"");
        session.setAttribute("roleList", roleList);

        return R.OK();
    }

    /**
     * 注销
     *
     * @return
     */
    @RequestMapping("logout")
    public String logout(HttpSession session) {
        //清空session
        session.invalidate();
        return "login";
    }

    /**
     * 跳转到登录页面
     *
     * @return
     */
    @RequestMapping("tologin")
    public String tologin() {

        return "login";
    }

    /**
     * 发送验证码
     * @param phone
     * @return
     */
    @ResponseBody
    @RequestMapping("sendCode")
    public R sendCode(String phone) {
        //产生验证码
        String code = new RandomGenerator("1234567890", 4).generate();
        System.out.println("短信验证码:" + code);
        //发送验证码--给手机发送短信
        Boolean status = SmsUtil.sendCode(phone, code, "2", 3);
        //将验证码存储到redis中
        redisTemplate.opsForValue().set(phone, code, 1, TimeUnit.MINUTES);
        return status ? R.OK(code) : R.ERROR(500, "发送失败");


    }

    @Autowired
    RabbitTemplate rabbitTemplate;

    @ResponseBody
    @RequestMapping("sendMsg")
    public R  sendMsg(){

        rabbitTemplate.convertAndSend("DIRECT_EX","roKey5","hello rabbitmq");
        return R.OK();
    }
}
